<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline>
      <el-form-item :label="t('orderReturn.returnorder_no')">
        <el-input
          v-model="form.returnorder_no"
          clearable
          :placeholder="t('orderReturn.returnorder_no')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('orderReturn.customer_id')">
        <el-input v-model="form.customer_name" clearable disabled style="width: 250px" />
        <el-button class="m-l-20px" size="small" type="primary" @click="handleOpenCustomer"
          >{{ t('wholesalOrder.selectCustomers') }}
        </el-button>
      </el-form-item>
      <el-form-item :label="t('orderReturn.signatory')" prop="signatory">
        <el-select
          v-model="form.signatory"
          :filterable="true"
          :placeholder="t('orderReturn.signatory')"
          :clearable="false"
          style="width: 150px"
        >
          <el-option
            v-for="item in operatorList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('orderReturn.signing_date')">
        <el-date-picker
          v-model="form.date"
          type="daterange"
          format="YYYY/MM/DD"
          range-separator="-"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          @change="changeTime"
          :editable="false"
          unlink-panels
        />
      </el-form-item>

      <el-form-item :label="t('orderReturn.total_amount')" prop="total_amount">
        <el-input-number
          v-model="form.min_total_amount"
          :min="1"
          :max="10000000"
          size="small"
          controls-position="right"
        />
        &nbsp;~&nbsp;
        <el-input-number
          v-model="form.max_total_amount"
          :min="1"
          :max="10000000"
          size="small"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item :label="t('orderReturn.paid_amount')" prop="paid_amount">
        <el-input-number
          v-model="form.min_paid_amount"
          :min="1"
          :max="10000000"
          size="small"
          controls-position="right"
        />
        &nbsp;~&nbsp;
        <el-input-number
          v-model="form.max_paid_amount"
          :min="1"
          :max="10000000"
          size="small"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item :label="t('orderReturn.return_reason')" prop="return_reason">
        <el-select
          v-model="form.return_reason"
          :filterable="true"
          :placeholder="t('orderReturn.return_reason')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in reasonList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('orderReturn.returnorder_type')" prop="returnorder_type">
        <el-select
          v-model="form.returnorder_type"
          :filterable="true"
          :placeholder="t('orderReturn.returnorder_type')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in returnorderTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <div class="flex flex-items-center my-5">
      <el-button type="primary" @click="handleJump('add')">
        {{ t('system.marketChannel.add') }}
      </el-button>
    </div>
    <!-- 表格主体 -->
    <el-table
      :data="dataList"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column :label="t('expandCustomer.serialNumber')" prop="id" min-width="70" />
      <el-table-column
        :label="t('orderReturn.returnorder_no')"
        min-width="250"
        :show-overflow-tooltip="true"
        prop="returnorder_no"
      />
      <el-table-column
        :label="t('orderReturn.returnorder_type')"
        min-width="250"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(returnorderTypeList, row.returnorder_type) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('orderReturn.customer_name')"
        prop="customer_name"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <!--      <el-table-column-->
      <!--          :label="t('orderReturn.order_no')"-->
      <!--          prop="order_no"-->
      <!--          min-width="200"-->
      <!--          :show-overflow-tooltip="true"-->
      <!--      />-->
      <el-table-column
        :label="t('orderReturn.order_type')"
        prop="order_type"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(orderTypeList, row.order_type) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('orderReturn.signatory')"
        prop="signatory"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(operatorList, row.signatory) }}
        </template>
      </el-table-column>

      <el-table-column
        :label="t('orderReturn.total_amount')"
        prop="total_amount"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('orderReturn.paid_amount')"
        prop="paid_amount"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('orderReturn.status')"
        prop="status"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(statusList, row.status) }}
        </template>
      </el-table-column>

      <el-table-column
        :label="t('supply.create_time')"
        min-width="180"
        prop="create_time"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('supply.creator')"
        min-width="100"
        prop="creator"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(operatorList, row.creator) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('supply.update_time')"
        min-width="180"
        prop="update_time"
        :show-overflow-tooltip="true"
      />

      <el-table-column fixed="right" label="操作" width="280">
        <template #default="{ row }">
          <el-button v-if="row.status === 1" @click="handleJump('edit', row)" size="small">
            {{ t('system.marketChannel.edit') }}
          </el-button>
          <el-button
            type="primary"
            v-if="row.status === 1"
            @click="examineHandle(row)"
            size="small"
          >
            {{ t('orderReturn.examine') }}
          </el-button>
          <el-button
            type="primary"
            v-if="row.status === 2"
            @click="uploadPayment(row)"
            size="small"
          >
            {{ t('orderReturn.orderUpload') }}
          </el-button>
          <el-button type="success" @click="handleJump('detail', row)" size="small">
            {{ t('action.detail') }}
          </el-button>
          <el-button
            v-if="row.status === 1"
            type="danger"
            @click="handleCancel('single', row)"
            size="small"
          >
            {{ t('common.cancel') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>

  <DialogCustomerChecked
    ref="DialogCustomerCheckedRef"
    @expose-multiple-data="getExposeCustomerData"
  />
  <!--      上传支付审核弹框-->
  <DialogUpload ref="DialogUploadRef" @refresh="initialize" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { cancelDataApi, getEnumApi, getListApi, examineDataApi } from '@/api/orderReturn'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { useClipboard } from '@vueuse/core'
import DialogCustomerChecked from '@/views/Order/OrderReturn/components/DialogCustomerChecked/index.vue'
import DialogUpload from '@/views/Order/OrderReturn/components/DialogUpload/index.vue'

const { copy } = useClipboard()
const { t } = useI18n()
const { push } = useRouter()

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const DialogCustomerCheckedRef = ref()
const DialogUploadRef = ref<InstanceType<typeof DialogUpload>>()

const paginationTotal = ref<number>(0)
const form = ref<Record<string, any>>({
  returnorder_no: '',
  customer_name: '',
  owner: '',
  date: '',
  min_total_amount: undefined,
  max_total_amount: undefined,
  min_paid_amount: undefined,
  max_paid_amount: undefined,
  return_reason: '',
  signing_start_date: '',
  signing_end_date: '',
  pageIndex: 1,
  pageSize: 20
})

const modelList = ref<Array<Record<string, any>>>([])
const operatorList = ref<Array<Record<string, any>>>([])
const reasonList = ref<Array<Record<string, any>>>([])
const returnorderTypeList = ref<Array<Record<string, any>>>([])
const orderTypeList = ref<Array<Record<string, any>>>([])
const statusList = ref<Array<Record<string, any>>>([])

//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.signing_start_date = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.signing_end_date = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.signing_start_date = null
    form.value.signing_end_date = null
  }
}

//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

//点击跳转
const handleJump = (type: string, row?: Record<string, any>) => {
  push({
    path: `/order/orderReturn/${type}`,
    query: { [(row && 'id') as string]: row?.id }
  })
}

//点击取消
const handleCancel = (type: string, row: Record<string, any>) => {
  ElMessageBox.confirm(t('orderReturn.confirmCancel'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await cancelDataApi({
        id:
          type === 'single'
            ? row.id
            : multipleSelection.value.map((item: Record<string, any>) => item.id)
      })
      ElMessage.success(t('orderReturn.cancelSuccess'))
      await initialize()
    })
    .catch(() => {})
}

const examineHandle = (row) => {
  ElMessageBox.confirm(
    '审核通过后订单状态不可回退，请确认数据无误后谨慎操作。',
    t('purchase.logistics.tips'),
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      const resp = await examineDataApi(row.id)
      if (resp.code === 0) {
        ElMessage.success(t('order.approvedMsg'))
        initialize()
      }
    })
    .catch(() => {})
}

const uploadPayment = (row: Record<string, any>) => {
  nextTick(() => {
    DialogUploadRef.value!.dialogVisible = true
    DialogUploadRef.value?.getBackShow(JSON.parse(JSON.stringify(row)))
  })
}

//打开选择客户弹框
const handleOpenCustomer = () => {
  nextTick(() => {
    DialogCustomerCheckedRef!.value!.dialogVisible = true
    DialogCustomerCheckedRef!.value!.initialize(
      form.value.user_id ? [{ ...form.value, id: form.value.user_id }] : []
    )
  })
}

//接收勾选中的客户
const getExposeCustomerData = (val: any[]) => {
  if (!val || !val.length) return
  form.value.customer_id = val[0].id
  form.value.customer_name = val[0].cusname
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  modelList.value = resp.data.model
  operatorList.value = resp.data.operator
  reasonList.value = resp.data.return_reason
  returnorderTypeList.value = resp.data.returnorder_type
  orderTypeList.value = resp.data.order_type
  statusList.value = resp.data.status
}

//根据接口枚举匹配出中文名称
const useEnumeratePicker = (
  enumList: any[],
  field: string | number,
  key?: string,
  value?: string
) => {
  if (!enumList) return
  const matchItem =
    enumList.find((item: Record<string, any>) => item[value ?? 'value'] === field) || {}
  return matchItem[key ?? 'label'] || ''
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = () => {
  form.value = {
    video_title: '',
    signing_start_date: '',
    signing_end_date: '',
    pageIndex: 1,
    pageSize: 20
  }
  paginationTotal.value = 0
  initialize()
}

onMounted(() => {
  getDropDownBoxInfo()
  initialize()
})
</script>

<style lang="less" scoped></style>
